using Microsoft.AspNetCore.Mvc;
using DeathReportManagement.Services;

namespace DeathReportManagement.Controllers;

[ApiController]
[Route("api/[controller]")]
public class Icd10Controller : ControllerBase
{
    private readonly Icd10Service _icd10Service;

    public Icd10Controller(Icd10Service icd10Service)
    {
        _icd10Service = icd10Service;
    }

    /// <summary>
    /// 搜索ICD10编码
    /// </summary>
    /// <param name="keyword">关键词</param>
    /// <param name="limit">返回数量限制</param>
    /// <returns>ICD10编码列表</returns>
    [HttpGet("search")]
    public async Task<IActionResult> Search(string keyword, int limit = 20)
    {
        if (string.IsNullOrWhiteSpace(keyword))
        {
            return Ok(new List<object>());
        }

        try
        {
            var results = await _icd10Service.SearchAsync(keyword, limit);
            var response = results.Select(x => new
            {
                code = x.Code,
                name = x.Name,
                category = x.Category,
                description = x.Description
            });

            return Ok(response);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { error = "搜索失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 根据编码获取ICD10信息
    /// </summary>
    /// <param name="code">ICD10编码</param>
    /// <returns>ICD10信息</returns>
    [HttpGet("{code}")]
    public async Task<IActionResult> GetByCode(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            return BadRequest("编码不能为空");
        }

        try
        {
            var result = await _icd10Service.GetByCodeAsync(code);
            if (result == null)
            {
                return NotFound("未找到对应的ICD10编码");
            }

            var response = new
            {
                code = result.Code,
                name = result.Name,
                category = result.Category,
                description = result.Description
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { error = "获取失败", message = ex.Message });
        }
    }
}